package com.doraemon.module.buyer.service.impl;

import com.doraemon.module.buyer.dao.ProductInfoDao;
import com.doraemon.module.buyer.dto.CartDTO;
import com.doraemon.module.buyer.entity.ProductInfo;
import com.doraemon.enums.ProductStateEnum;
import com.doraemon.enums.ResultEnum;
import com.doraemon.common.exception.SellException;
import com.doraemon.module.buyer.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *商品信息业务类
 * @author doraemon
 * @date 2017/9/12
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService {
    @Autowired
    private ProductInfoDao productInfoDao;
    @Override
    public ProductInfo findOne(String productInfoId) {
        return productInfoDao.findOne(productInfoId);
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return productInfoDao.findAll(pageable);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoDao.findByProductStatus(ProductStateEnum.UP.getCode());
    }
    
    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return productInfoDao.save(productInfo);
    }

    @Override
    public void decreaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = productInfoDao.findOne(cartDTO.getProductId());
            if (productInfo == null) {
                throw  new SellException(ResultEnum.PRODUCT_NOT_FOUND);
            }
            Integer productStorck = productInfo.getProductStock()-cartDTO.getProductQuantity();
            if(productStorck<0){
                throw new SellException(ResultEnum.PRODUCT_STORCK_ERROR);
            }
            productInfo.setProductStock(productStorck);
            productInfoDao.save(productInfo);
        }
    }

    @Override
    public void increaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = productInfoDao.findOne(cartDTO.getProductId());
            if (productInfo == null) {
                throw  new SellException(ResultEnum.PRODUCT_NOT_FOUND);
            }
            Integer productStorck = productInfo.getProductStock()+cartDTO.getProductQuantity();

            productInfo.setProductStock(productStorck);
            productInfoDao.save(productInfo);
        }
    }
}
